<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>四则运算</title>
</head>
<body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<div id="ato">
    <div class="row">
        操作数1：<input type="text" name="num1" placeholder="操作数1">
    </div>
    <div class="row">
        运算符：<input type="text" name="str" placeholder="运算符">
    </div>
    <div class="row">
        操作数2：<input type="text" name="num2" placeholder="操作数2">
    </div>
    <div class="row">
        <button >计算</button>
    </div>
    <div class="row" id="result">
        计算结果：
    </div>
    <div class="row">
        历史记录：
    </div>
</div>

<script>
    let ato=document.querySelector('#ato');
    let btn=document.querySelector('button');
    btn.onclick=function(){
        let inputs= document.querySelectorAll('input');
        let num1=inputs[0].value;
        let str=inputs[1].value;
        let num2=inputs[2].value;
        for(let i=0;i<inputs.length;i++){
            if(num1==''||str==''||num2==''){
                alert("输入元素不能为空！")
                return;
            }
        }
        //点击按钮，直接发送post请求，把页面上的数据传过去
        data1={
            num1:num1,
            str:str,
            num2:num2
        }
        $.ajax({
            method:'post',
            url:'save',
            data:data1,
            success:function (body) {
                if(body==-1){
                    console.log("数据插入失败")
                }
                let result=document.querySelector('#result');
                result.innerHTML="计算结果: "+body;
                console.log("数据插入成功")
            }
        });

    }
    function getCalcList() {
        $.ajax({
            method: 'get',
            url:'load',
            success:function (body) {
                console.log(body);
                for(let i=0;i< body.length;i++){
                    let newDiv2=document.createElement('div');
                    newDiv2.className='row';
                    let massage = body[i];
                    newDiv2.innerHTML=massage.time+" "+massage.num1+massage.str+massage.num2+"="+massage.result;
                    ato.appendChild(newDiv2);
                    console.log("数据获取成功")
                }
            }
        });
    }
    getCalcList();
</script>
</body>
</html>